package com.cuit.qx.job;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cuit.qx.bean.WeatherStation;
import com.cuit.qx.entity.CorrectForecast;
import com.cuit.qx.entity.InterfaceMonitoring;
import com.cuit.qx.service.*;
import com.cuit.qx.utils.HttpUtil;
import com.cuit.qx.utils.JsonUtil;
import com.cuit.qx.utils.WebSocket;
import groovy.util.logging.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.ConnectException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:wjd
 * @Description:  定时任务处理
 * @date:Created in 17:04 2020/9/21
 * @Modified By:
 */
@EnableScheduling
@Slf4j
@EnableAsync
@Component
public class TimingProcessorJob {
    private static final Logger LOG = LoggerFactory.getLogger(TimingProcessorJob.class);

    @Autowired
    StationInfoService serviceinfo;
    @Autowired
    CorrectForecastService service;
    @Autowired
    InterfaceMonitoringService interfaceMonitoringService;
    @Autowired
    WeatherStationService stationService;
    @Autowired
    TQservice tQservice;


    //气象站点数据
    @Async
//    @Scheduled(cron = "0 30 1 * * ? ")
    public void liveToHistoricalMonth() {
        LOG.info("================Zhengli weather info data insert start===============");
        serviceinfo.execute();
        LOG.info("================Zhengli weather info data insert end===============");
    }

    //天擎数据
    @Async
//    @Scheduled(cron = "0 0 1 * * ? ")
    public void tianQData() {
        LOG.info("================天擎数据采集开始===============");
        tQservice.C1D_GLB_FOR();
        tQservice.GRAPES_3KM_SC();
        tQservice.GRAPES_CFSV2();
        tQservice.SURF_CHN_MUL_HOR();
        tQservice.SURF_CHN_MUL_HOR_N();
        LOG.info("================天擎数据采集结束===============");
    }


    @Async
//    @Scheduled(cron = "0 0/2 * * * ? ")
    public void getCorrectForecast() {
        LOG.info("==================执行订正预报数据采集开始======================");
        //TODO fileName根据实际文件情况进行动态生成。待服务器、网络接通后开发。
        patternTransitionJob("/data/home/lisiyan/data/wuzhou","2022020100");
//        patternTransitionJob("/home/MicapsZip/",fileName,"20");
        LOG.info("==================执行订正预报数据采集结束======================");
    }

    public void patternTransitionJob(String micapszip,String startDate){
        String data = "";
        InterfaceMonitoring monitoring = new InterfaceMonitoring();
        monitoring.setExecutionTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        monitoring.setId("482a6c6b1640682720019");
        monitoring.setInterfaceNum(2);
        try {
            data = new HttpUtil().doGet("http://58.217.204.132:8001/correctForecast/rain_forecast?micapszip=/data/home/lisiyan/data/wuzhou&startnum=2022020100");
            String[] patterns = {"ec", "grapes", "huanan", "correct"};
            System.out.println("data:::"+data);
            if (null == data) {
                LOG.info("订正预报接口请求数据为空" + data);
                monitoring.setDescription("订正预报接口数据为空");
                return;
            }
            monitoring.setState(0);
            monitoring.setDescription("接口采集正常");

            for (int i = 0; i < patterns.length; i++) {
                JSONObject jsonObject = JSONObject.fromObject(data);
                Object ec = jsonObject.get(patterns[i]);
                JSONObject jsonObject1 = JSONObject.fromObject(ec);
                String station = jsonObject1.get("station").toString();

                HashMap map = JSON.parseObject(station, HashMap.class);

                Iterator iterator = map.keySet().iterator();

                while (iterator.hasNext()) {
                    Object key = iterator.next();
                    CorrectForecast correctForecast = new CorrectForecast();
                    correctForecast.setPattern(patternTransition(patterns[i]));//模式转换
                    correctForecast.setStationId((String) key);
                    String[] bytes = map.get(key).toString().replace("[", "").replace("]", "").split(",");
                    correctForecast.setTime3(bytes[0]);
                    correctForecast.setTime6(bytes[1]);
                    correctForecast.setTime9(bytes[2]);
                    correctForecast.setTime12(bytes[3]);
                    correctForecast.setTime15(bytes[4]);
                    correctForecast.setTime18(bytes[5]);
                    correctForecast.setTime21(bytes[6]);
                    correctForecast.setTime24(bytes[7]);
                    correctForecast.setTime27(bytes[8]);
                    correctForecast.setTime30(bytes[9]);
                    correctForecast.setTime33(bytes[10]);
                    correctForecast.setTime36(bytes[11]);
                    correctForecast.setTime39(bytes[12]);
                    correctForecast.setTime42(bytes[13]);
                    correctForecast.setTime45(bytes[14]);
                    correctForecast.setTime48(bytes[15]);
                    correctForecast.setTime51(bytes[16]);
                    correctForecast.setTime54(bytes[17]);
                    correctForecast.setTime57(bytes[18]);
                    correctForecast.setTime60(bytes[19]);
                    correctForecast.setTime63(bytes[20]);
                    correctForecast.setTime66(bytes[21]);
                    correctForecast.setTime69(bytes[22]);
                    correctForecast.setTime72(bytes[23]);
                    correctForecast.setId(UUID.randomUUID().toString().substring(0, 12));
                    LambdaQueryWrapper<WeatherStation> queryWrapper = new LambdaQueryWrapper();
                    LambdaQueryWrapper<WeatherStation> eq = queryWrapper.eq(WeatherStation::getStationNumber, (String) key);
                    WeatherStation one = stationService.getOne(eq);
                    correctForecast.setLat(String.valueOf(one.getLatitude()));
                    correctForecast.setLon(String.valueOf(one.getLongitude()));
                    correctForecast.setStartTime(Integer.parseInt(startDate));
                    correctForecast.setStartDate(timeAdd(startDate).substring(8,10));
                    correctForecast.setRemark(one.getStationCounty());
                    correctForecast.setStaionName(one.getStationName());
                    service.save(correctForecast);
                }
            }
        } catch (Exception e) {
            monitoring.setState(1);
            monitoring.setDescription("接口异常" + e);
            LOG.error("订正预报采集异常", e);
        }


        interfaceMonitoringService.updateById(monitoring);

    }

    public int patternTransition(String pattern) {
        int pa = 0;
        switch (pattern) {
            case "grapes":
                pa = 0;
                break;
            case "ec":
                pa = 1;
                break;
            case "huanan":
                pa = 2;
                break;
            case "correct":
                pa = 3;
                break;
        }
        return pa;
    }

    //加8小时
    public String timeAdd(String time){
        SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHH");
        Date d  = null;
        try {
            d = sd.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long rightTime = (long) (d.getTime() + 8 * 60 * 60 * 1000);

        return sd.format(rightTime);
    }

    public static void main(String[] args) throws ParseException {



    }
}
